package cn.zgz.dbhelper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.zgz.mapper.IRowMapper;


public class DBHelper {
	String url = "jdbc:mysql://localhost:3306/demmannager?serverTimezone=UTC";
	String userName = "root";
	String userPass = "";
	Connection conn = null;
	PreparedStatement pstat = null;
	ResultSet rs = null;
	public void getConnection() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.cj.jdbc.Driver");
		conn = DriverManager.getConnection(url, userName, userPass);
	}
	public void setprepared(Object...objects) throws SQLException{
		if(objects!=null&&objects.length>0){
			for(int i =0;i<objects.length;i++){
				pstat.setObject(i+1, objects[i]);
			}
		}
	}
	public int excuteUpdate(String sql, Object...objects) throws ClassNotFoundException, SQLException{
		getConnection();
		pstat = conn.prepareStatement(sql);
		setprepared(objects);
		return pstat.executeUpdate();
	}
	public ResultSet excuteQuery(String sql, Object...objects) throws ClassNotFoundException, SQLException{
		getConnection();
		pstat = conn.prepareStatement(sql);
		setprepared(objects);
		ResultSet rs = pstat.executeQuery();
		return rs;
	}
	public <T> List<T> excuteQuery(String sql,IRowMapper<T> mapper, Object...objects) throws Exception{
		getConnection();
		pstat = conn.prepareStatement(sql);
		setprepared(objects);
		rs = pstat.executeQuery();
		List<T> tlist = new ArrayList<T>();
		while(rs.next()) {
			T t = mapper.rowMapper(rs);
			tlist.add(t);
		}
		return tlist;
	}
	public void colse() throws SQLException{
		if(rs!=null){
			rs.close();
		}
		if(pstat!=null){
			pstat.close();
		}
		if(conn!=null){
			conn.close();
		}
	}
}
